package com.choosefine.it.team.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.choosefine.it.base.BaseController;
import com.choosefine.it.base.dto.PageDTO;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.exception.BusinessException;
import com.choosefine.it.common.model.CustomRestTemplate;
import com.choosefine.it.common.utils.DateUtils;
import com.choosefine.it.common.utils.IdsUtil;
import com.choosefine.it.common.utils.IntegerUtil;
import com.choosefine.it.common.utils.StringUtils;
import com.choosefine.it.team.model.TeamPublishFindWorkerInfo;
import com.choosefine.it.team.model.dto.TeamRecruitmentInfoSelectDTO;
import com.choosefine.it.team.model.dto.UpdateRecruitmentVerifyStatusDTO;
import com.choosefine.it.team.model.vo.TeamRecruitmentInfoMobileVO;
import com.choosefine.it.team.service.TeamPublishFindWorkerInfoService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/team/TeamRecruitmentInfo")
@Api(value = "班组发布招工以及管理相关", description = "鞠成阳")
public class TeamPublishFindWorkerInfoController extends BaseController {
	@Autowired
	private TeamPublishFindWorkerInfoService teamPublishFindWorkerInfoService;
	@Autowired
	CustomRestTemplate restTemplate;
	@Autowired
	ObjectMapper jsonObjectMapper;
	Logger logger = LoggerFactory.getLogger(TeamPublishFindWorkerInfoController.class);

	@Value("#{yaml.get('basedata.userinfo.getUserByUserCode')}")
	final String userinfoURL = null;

	/**
	 * 发布招工信息
	 * 
	 * @param
	 * @return
	 * @throws JsonProcessingException
	 */
	@ApiOperation("添加找招工信息")
	@RequestMapping(method = RequestMethod.POST, value = "/publish", produces = "application/json")
	public String publish(@RequestBody TeamPublishFindWorkerInfo teamPublishFindWorkerInfo)
			throws JsonProcessingException, BusinessException {
		String result = null;
		if (teamPublishFindWorkerInfo != null && StringUtils.isNotBlank(teamPublishFindWorkerInfo.getUserCode())) {
			Long isSuccess = teamPublishFindWorkerInfoService.addTeamRecruitmentInfo(teamPublishFindWorkerInfo);
			if (isSuccess.longValue() > 0) {
				result = responseSuccess(isSuccess, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS);
			} else {
				result = responseFail(ResultCode.FAILED, ResultCode.MSG_CREATE_ERROR);
			}
		}
		return result;
	}

	/**
	 * 根据userCode查询招工信息列表
	 * 
	 * @return
	 */
	@ApiOperation(value = "获取班组发布招工的列表", notes = "根据userCode和需要分页的参数来查询班组发布招工的列表", response = TeamRecruitmentInfoMobileVO.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userCode", value = "用户的唯一编号", required = true, dataType = "String", paramType = "path"),
			@ApiImplicitParam(name = "pageNum", value = "起始行", required = true, dataType = "Integer", paramType = "path"),
			@ApiImplicitParam(name = "pageSize", value = "一页显示行数", required = true, dataType = "Integer", paramType = "path"),
			@ApiImplicitParam(name = "verifyStatus", value = "审核状态", required = true, dataType = "Integer", paramType = "path")})
	@RequestMapping(method = RequestMethod.GET, value = "/getteamRecruitmentInfoList/{userCode}/{pageNum}/{pageSize}/{verifyStatus}")
	public String getTeamRecruitmentInfoList(@PathVariable String userCode, @PathVariable Integer pageNum,
			@PathVariable Integer pageSize, @PathVariable Integer verifyStatus) throws BusinessException {
		String result = null;
		PageDTO page = new PageDTO();
		page.setPageNum(pageNum);
		page.setPageSize(pageSize);
		Map<String, Object> params = new HashMap<>();
		params.put("userCode", userCode);
		params.put("isValid", 0);// 0代表有效1代表无效
		params.put("verifyStatus", verifyStatus);// updpate by juchengyang 2017/2/25
		Page<TeamPublishFindWorkerInfo> list = teamPublishFindWorkerInfoService.getTeamRecruitmentInfoList(params, page);
		if (list.size() > 0) {
			result = responseSuccess(list);
		} else {
			result = responseFail(ResultCode.FAILED, ResultCode.MSG_DATA_ISEMPTY);
		}
		return result;
	}

	/**
	 * 根据id修改某条招聘信息的状态
	 * 
	 * @param
	 * @param id
	 * @return
	 */
	@ApiOperation(value = "修改某条发布招工信息的发布状态", notes = "")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "publishStatus", value = "发布状态0开始招聘1停止招聘", required = true, dataType = "Integer", paramType = "path"),
			@ApiImplicitParam(name = "id", value = "该条记录的id", required = true, dataType = "Integer", paramType = "path") })
	@RequestMapping(method = RequestMethod.PUT, value = "/updatePublishstatus/{publishStatus}/{id}", produces = "application/json")
	public String updatePublishstatusByID(@PathVariable Integer publishStatus, @PathVariable Integer id) {
		String result = null;
		if (IntegerUtil.isNotZero(id)) {
			Map<String, Object> params = new HashMap<>();
			params.put("publishStatus", publishStatus);// 发布状态（0开始招聘1停止招聘）
			params.put("id", id);
			params.put("utime", DateUtils.getNowTime());
			Integer num = teamPublishFindWorkerInfoService.updatePublishstatusByID(params);
			if (num.intValue() > 0) {
				result = responseSuccess(num, ResultCode.SUCCESS, "修改成功");
			} else {
				result = responseFail(ResultCode.MSG_ERROR);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	/**
	 * 根据id软删除某条招聘信息
	 * 
	 * @param id
	 * @return
	 */
	@ApiOperation(value = "修改某条发布招工信息的数据有效性", notes = "")
	@ApiImplicitParam(name = "id", value = "该条记录的id", required = true, dataType = "Integer", paramType = "path")
	@RequestMapping(method = RequestMethod.PUT, value = "/deleteTeamRecruitmentInfo/{id}", produces = "application/json")
	public String deleteTeamRecruitmentInfo(@PathVariable Integer id) {
		String result = null;
		if (IntegerUtil.isNotZero(id)) {
			Map<String, Object> params = new HashMap<>();
			params.put("id", id);
			params.put("utime", DateUtils.getNowTime());
			Integer num = teamPublishFindWorkerInfoService.deleteTeamRecruitmentInfo(params);
			if (num.intValue() > 0) {
				result = responseSuccess(num, ResultCode.SUCCESS, ResultCode.MSG_DELETE_SUCCESS);
			} else {
				result = responseFail(ResultCode.FAILED, ResultCode.MSG_DELETE_FAILD);
			}

		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	/**
	 * 根据id更新某条发布信息
	 * 
	 * @throws JsonProcessingException
	 */
	@ApiOperation(value = "修改某条发布招工信息的详情", notes = "")
	@ResponseBody
	@ApiResponses({ @ApiResponse(code = ResultCode.SUCCESS_CREATED, message = "添加成功返回结果"),
			@ApiResponse(code = ResultCode.FAILED, message = "请求参数错误") })
	@RequestMapping(value = "/updateTeamRecruitmentInfo", method = RequestMethod.PUT)
	public String updateTeamRecruitmentInfo(@RequestBody TeamPublishFindWorkerInfo teamRecruitmentInfo)
			throws JsonProcessingException {
		String result = null;
		//用户usercode不为空
		if (teamRecruitmentInfo.getUserCode() != null 
				&& !"".equals(teamRecruitmentInfo.getUserCode())) {
			Integer isSuccess = teamPublishFindWorkerInfoService.updateTeamRecruitmentInfoByID(teamRecruitmentInfo);
			if (isSuccess.intValue() > 0) {
				result = responseSuccess(isSuccess, ResultCode.SUCCESS, ResultCode.MSG_UPDATE_SUCCESS);
			} else {
				result = responseFail(ResultCode.FAILED, ResultCode.MSG_UPDATE_FAILD);
			}
		} else {
			result = responseFail(ResultCode.FAILED, ResultCode.MSG_USERNOTEXIT);
		}
		return result;
	}

	/**
	 * 根据id查询某条发布信息的详情
	 * 
	 * @param id
	 * @return
	 */
	@ApiOperation(value = "根据该条发布记录的id查询信息详情", notes = "", response = TeamPublishFindWorkerInfo.class)
	@ApiImplicitParam(name = "id", value = "发布招工的id", required = true, dataType = "Integer", paramType = "path")
	@RequestMapping(value = "/selectTeamRecruitmentInfoDetail/{id}", method = RequestMethod.GET)
	public String selectTeamRecruitmentInfoDetail(@PathVariable Integer id) {
		String result = null;
		if (IntegerUtil.isNotZero(id)) {
			TeamPublishFindWorkerInfo teamPublishFindWorkerInfo = teamPublishFindWorkerInfoService.selectTeamRecruitmentInfoDetail(id);
			if (teamPublishFindWorkerInfo != null) {
				result = responseSuccess(teamPublishFindWorkerInfo, ResultCode.SUCCESS, ResultCode.MSG_QUERY_SUCCESS);
			} else {
				result = responseFail(ResultCode.FAILED, ResultCode.MSG_DATA_ISEMPTY);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	@ApiIgnore
//	@ApiOperation(value = "获取班组招工列表", notes = "")
	@RequestMapping(value = "/getCheckingTeamRecruitmentInfoList", method = RequestMethod.POST)
	public String selectTeamRecruitmentInfoByVerifyStatus(@RequestBody TeamRecruitmentInfoSelectDTO teamRecruitmentInfoSelectDTO) throws JsonProcessingException {
		String result = null;
		PageDTO page = new PageDTO();
		page.setPageNum(teamRecruitmentInfoSelectDTO.getPageNum());
		page.setPageSize(teamRecruitmentInfoSelectDTO.getPageSize());
		Map<String, Object> params = new HashMap<>();
		if (teamRecruitmentInfoSelectDTO.getWorkTypeId() != null) {
			params.put("workTypeId", teamRecruitmentInfoSelectDTO.getWorkTypeId());
		}
		if (teamRecruitmentInfoSelectDTO.getWorkTypeName() != null) {
			params.put("workTypeName", teamRecruitmentInfoSelectDTO.getWorkTypeName());
		}
		if (teamRecruitmentInfoSelectDTO.getUserCode() != null && !"".equals(teamRecruitmentInfoSelectDTO.getUserCode())) {
			params.put("userCode", teamRecruitmentInfoSelectDTO.getUserCode());
		}
		if (teamRecruitmentInfoSelectDTO.getProjectName() != null && !"".equals(teamRecruitmentInfoSelectDTO.getProjectName())){
			params.put("projectName", teamRecruitmentInfoSelectDTO.getProjectName());
		}
		if (teamRecruitmentInfoSelectDTO.getStartTime() != null) {
			params.put("startTime", teamRecruitmentInfoSelectDTO.getStartTime());
		}
		if (teamRecruitmentInfoSelectDTO.getEndTime() != null) {
			params.put("endTime", teamRecruitmentInfoSelectDTO.getEndTime());
		}
		if (teamRecruitmentInfoSelectDTO.getVerifyStatus() != null) {
			params.put("verifyStatus", teamRecruitmentInfoSelectDTO.getVerifyStatus());
		}
		Page<TeamPublishFindWorkerInfo> list = teamPublishFindWorkerInfoService.selectRecruitmentInfoByCondition(params, page);
		result = responseSuccess(list.toPageInfo());
		return result;
	}

	@ApiIgnore
	@RequestMapping(value = "/deleteTeamRecruitmentInfo/{idss}", method = RequestMethod.GET)
	public String deleteTeamRecruitmentInfo(@PathVariable String idss) {
		List<Integer> ids = new ArrayList<>();
		String result = null;
		ids = IdsUtil.getIds(idss);
		Map<String, Object> params = new HashMap<>();
		if (ids.size() > 0) {
			params.put("ids", ids);
			params.put("utime", DateUtils.getNowTime());
			int isSuccess = teamPublishFindWorkerInfoService.deleteTeamRecruitment(params);
			if (isSuccess == ids.size()) {
				result = responseSuccess(isSuccess, ResultCode.SUCCESS, ResultCode.MSG_DELETE_SUCCESS);
			} else if (0 < isSuccess && isSuccess < ids.size()) {
				result = responseSuccess(isSuccess, ResultCode.FAILED, ResultCode.MSG_UPDATEPART_SUCCESS);
			} else {
				result = responseFail(ResultCode.FAILED, ResultCode.MSG_UPDATE_FAILD);
			}
		} else {
			responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

//	@ApiIgnore
	@RequestMapping(value = "/updateTeamRecruitmentVerifyStatus", method = RequestMethod.PUT)
	public String updateRecruitmentVerifyStatus(@RequestBody UpdateRecruitmentVerifyStatusDTO dto) {
		String result = null;
		Map<String, Object> params = new HashMap<>();
		if (null != dto.getId() 
				&& StringUtils.isNotEmpty(dto.getPublisher())
				&& null != dto.getVerifyStatus()) {
			params.put("id", dto.getId());
			params.put("verifyStatus", dto.getVerifyStatus());
			params.put("publisher", dto.getPublisher());
			if(StringUtils.isNotEmpty(dto.getReason())){
				params.put("reason", dto.getReason());
			}
			params.put("utime", DateUtils.getNowTime());
			int isSuccess = teamPublishFindWorkerInfoService.updateRecruitmentVerifyStatus(params);
			if (isSuccess > 0) {
				result = responseSuccess(isSuccess, ResultCode.MSG_UPDATE_SUCCESS);
			} else {
				result = responseFail(ResultCode.MSG_UPDATE_FAILD);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_ERROR);
		}
		return result;
	}

	@ApiOperation(value = "搜索班组找工人")
	@RequestMapping(value = "getrecruitmentinfo/{publishtime}/{publisher}/{worktype}/{pageNum}/{pageSize}", method = RequestMethod.GET)
	@ApiResponses({ @ApiResponse(code = ResultCode.SUCCESS_CREATED, message = "成功"),
			@ApiResponse(code = ResultCode.FAILED, message = "失败")

	})
	@ApiImplicitParams({
			@ApiImplicitParam(name = "publishtime", value = "发布的时间", dataType = "Long", required = true, defaultValue = "", paramType = "path"),
			@ApiImplicitParam(name = "publisher", value = "发布人", dataType = "String", required = true, defaultValue = "", paramType = "path"),
			@ApiImplicitParam(name = "worktype", value = "工种", dataType = "Integer", required = true, defaultValue = "", paramType = "path"),
			@ApiImplicitParam(name = "pageNum", value = "起始页", dataType = "int", required = true, paramType = "path"),
			@ApiImplicitParam(name = "pageSize", value = "每页行", dataType = "int", required = true, paramType = "path") })
	public String teamFindWork(@PathVariable Integer worktype, @PathVariable String publisher,
			@PathVariable Long publishtime, @PathVariable Integer pageNum, @PathVariable Integer pageSize)
			throws Exception {
		String result = null;
		PageDTO page = new PageDTO();
		page.setPageNum(pageNum);
		page.setPageSize(pageSize);
		if (worktype != null && publisher != null && publishtime != null) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("workType", worktype);
			params.put("publishTime", publishtime);
			params.put("publisher", publisher);
			List<TeamPublishFindWorkerInfo> a = teamPublishFindWorkerInfoService.select(params, page);
			result = responseSuccess(a);
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_ERROR);
		}
		return result;
	}

}
